import http from '../api/http'
import type { ApiResult } from './types'

// 订单列表项（与后端 OrderQueryResponseDto 对齐）
export interface OrderQueryItem {
  id?: string
  orderCode?: string
  orderAmount?: number
  orderType?: number
  payAmount?: number
  couponInstanceId?: string
  discountAmount?: number
  paymentTime?: string
  paymentStatus?: number
  creationTime?: string
  payMethod?: string
  storeName?: string
  codeName?: string
  orderSnapshot?: string
  totalRefundAmount?: number
}

// 订单详情（与后端 OrderResponseDto 对齐，字段尽量可选以兼容）
export interface OrderDetail {
  id?: string
  orderCode?: string
  orderAmount?: number
  orderType?: number
  codeId?: string
  storeId?: string
  merchantId?: string
  deviceId?: string
  rate?: number
  commission?: number
  couponInstanceId?: string
  discountAmount?: number
  settlementAmount?: number
  platformServiceFeeRate?: number
  platformServiceFee?: number
  paymentTime?: string
  paymentStatus?: number
  recommendationCommissionAmount?: number
  recommendMerchantId?: string
  userId?: string
  openId?: string
  dividedAgreementId?: string
  orderSnapshot?: string
  totalRefundAmount?: number
  refundCount?: number
  refundStatus?: number
  refundProcessStatus?: number
  refundTime?: string
  lastRefundTime?: string
  isSettlement?: number
  settlementDate?: string
  settlementTime?: string
  isDivided?: number
  dividedDate?: string
  dividedTime?: string
  outTradeNo?: string
  payAmount?: number
  payMethod?: string
  subAppId?: string
  buyerId?: string
  channelOrder?: string
  transactionNo?: string
  refundableAmount?: number
  extraProperties?: string
  concurrencyStamp?: string
  creationTime?: string
  creatorId?: string
  lastModificationTime?: string
  lastModifierId?: string
  isDeleted?: boolean
  deleterId?: string
  deletionTime?: string
  // 快照字段
  code?: string
  codeName?: string
  storeCode?: string
  storeName?: string
  merchantCode?: string
  merchantName?: string
  agreementCode?: string
  agreementName?: string
  dividedCycle?: number
  settlementCycle?: number
  snapshotTime?: string
}

// 订单退款记录（与后端 OrderRefundRecordResponseDto 对齐）
export interface OrderRefundRecordItem {
  id?: string
  orderId?: string
  customerCode?: string
  outRefundNo?: string
  outTradeNo?: string
  transactionNo?: string
  refundAmount?: number
  originalAmount?: number
  remark?: string
  procedureFee?: number
  refundTime?: string
  channelTradeNo?: string
  status?: number
  isAutoRefund?: boolean
  creationTime?: string
  lastModificationTime?: string
  extraProperties?: string
}

export interface OrderListParams {
  page?: number
  limit?: number
  key?: string
  storeId?: string
  merchantId?: string
  codeId?: string
  paymentStatus?: number
  isDividedAgreement?: boolean
  beginTime?: string
  endTime?: string
}

export class OrderService {
  // 获取订单列表（ToB）
  static async getOrdersListToB(params: OrderListParams = {}): Promise<ApiResult<{ total: number; data: OrderQueryItem[] }>> {
    const query: any = {
      page: params.page ?? 1,
      limit: params.limit ?? 10,
      key: params.key ?? '',
      storeId: params.storeId ?? '',
      merchantId: params.merchantId ?? '',
      codeId: params.codeId ?? '',
      paymentStatus: params.paymentStatus ?? 1,
      isDividedAgreement: params.isDividedAgreement,
      beginTime: params.beginTime,
      endTime: params.endTime
    }
    const resp = await http.get<ApiResult<{ total: number; data: OrderQueryItem[] }>>('/Payment/GetOrdersListToB', { params: query })
    return resp.data
  }

  // 获取订单详情（按 Id）
  static async getOrderDetail(id: string): Promise<ApiResult<OrderDetail>> {
    const resp = await http.get<ApiResult<OrderDetail>>('/Payment/GetOrders', { params: { Id: id } })
    return resp.data
  }

  // 获取订单退款记录列表
  static async getOrderRefundRecordList(orderId: string): Promise<ApiResult<OrderRefundRecordItem[]>> {
    const resp = await http.get<ApiResult<OrderRefundRecordItem[]>>('/Payment/GetOrderRefundRecordList', { params: { orderId } })
    return resp.data
  }
}

// 状态与支付方式文案
export const paymentStatusText = (s?: number): string => {
  switch (s) {
    case 0: return '处理中'
    case 1: return '支付成功'
    case 2: return '支付失败'
    case 3: return '已撤销'
    case 4: return '已关闭'
    case 5: return '已超时'
    default: return '未知'
  }
}

export const payMethodText = (m?: string): string => {
  if (!m) return '未知'
  // 后端返回为字符串（如 WeChatPay/Alipay），直接显示或做简单映射
  const map: Record<string, string> = {
    WeChatPay: '微信',
    Alipay: '支付宝'
  }
  return map[m] || m
}

